package com.zhr.tools.compile;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 根据实体类生成get、set...方法
 *
 * @author zhr
 */
public class GenGetSetTools {
    private static <T> List<String> getMethodWithPrefix(Class<T> clazz, String prefix) {
        List<String> list = new ArrayList<>();
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            String name = method.getName();
            if (name.startsWith(prefix)) {
                list.add(name);
            }
        }
        return list;
    }

    public static String gen(String javaCode, String methodPrefix, String genCodePrefix, String genCodeSuffix) throws Exception {
        Class clazz = EcjTool.compileJavaCode(javaCode, null);
        Object instance = clazz.newInstance();
        List<String> methods = getMethodWithPrefix(instance.getClass(), methodPrefix);
        StringBuilder sb = new StringBuilder();
        methods.forEach(e -> sb.append(genCodePrefix).append(e).append(genCodeSuffix).append("\r\n"));
        return sb.toString();
    }
}
